package com.ergwang.controller.mall;

import com.ergwang.Model.Goods;
import com.ergwang.Model.Result;
import com.ergwang.Model.mall.vo.SearchGoodsVO;
import com.ergwang.service.admin.GoodsService;
import com.ergwang.service.admin.GoodsServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author：ergwang
 * @Date: 2020/6/2
 * @Time: 10:44
 */
@WebServlet("/api/mall/goods/*")
public class GoodsServlet extends HttpServlet {

    private Gson gson = new Gson();
    private GoodsService goodsService = new GoodsServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/mall/goods/", "");
        if("getGoodsByType".equals(action)){
            getGoodsByType(request,response);
        }else if ("searchGoods".equals(action)){
            searchGoods(request,response);
        }
    }

    /**
     * 根据前端传来的keyword 模糊查询商品名，并返回商品信息
     * @param request
     * @param response
     */
    private void searchGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keyword = request.getParameter("keyword");
        List<SearchGoodsVO> goodsVO = goodsService.searchGoods(keyword);
        response.getWriter().println(gson.toJson(Result.ok(goodsVO)));
    }

    /**
     * 分类显示商品
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取前台传过来的typeId
        String typeId = request.getParameter("typeId");
        // 获取商品列表
        List<Goods> goodsByType = goodsService.getGoodsByType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goodsByType)));
    }
}
